from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver, Service
from selenium.webdriver.common.by import By
import platform
import getpass
import random
import time
import json
import os

system = platform.system()
if system.startswith('Windows'):
    EXEC_DIR_PATH = f'C:/Users/{getpass.getuser()}/AppData/Local/Google/Chrome/Application/chrome.exe'
    USER_DIR_PATH = f'C:/Users/{getpass.getuser()}/AppData/Local/Google/Chrome/User_Data'
elif system.startswith('Apple'):
    EXEC_DIR_PATH = f'/Users/{getpass.getuser()}/Library/Application Support/Google/Chrome/Application/chrome'
    USER_DIR_PATH = f'/Users/{getpass.getuser()}/Library/Application Support/Google/Chrome/User_Data'
elif system.startswith('Linux'):
    EXEC_DIR_PATH = f'/home/{getpass.getuser()}/AppData/Local/Google/Chrome/Application/chrome'
    USER_DIR_PATH = f'/home/{getpass.getuser()}/AppData/Local/Google/Chrome/User_Data'


def get_browser_1(page_url:str = None) -> WebDriver:
    # 浏览器配置对象
    options = webdriver.ChromeOptions()
    # 禁用自动化栏
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    # 屏蔽保存密码提示框
    options.add_experimental_option('prefs', {
        'credentials_enable_service': False,
        'profile.password_manager_enabled': False
    })
    # 窗口最大化
    options.add_argument("--start-maximized")
    # 无界面运行(无窗口), 也叫无头浏览器
    # options.add_argument("--headless")
    # 禁用GPU，防止无头模式出现莫名的bug
    # options.add_argument("--disable-gpu")
    # 禁用启用Blink运行时
    options.add_argument('--disable-blink-features=AutomationControlled')
    # options.binary_location = EXEC_DIR_PATH
    # service
    driver_path = f'F:\Projects Dev\python\demo2\chromedriver.exe'
    service = Service(executable_path=driver_path)
    driver = webdriver.Chrome(options=options, service=service)
    # 待执行的 JS 代码,修改 window.navigator.webdriver 的值
    # js_exec = 'Object.defineProperties(navigator,{webdriver:{get:() => undefined}});'
    # 移除selenium当中爬虫的特征
    # driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', '{"source", '+ js_exec +'}')
    # driver.implicitly_wait(10)
    if page_url is not None:
        # 设置域名
        driver.get(page_url[:page_url.find('/', 8)])
        # 加载cookie
        load_cookies(driver)
        # 刷新cookie
        save_cookies(driver)
        # 请求url
        driver.get(page_url)
    return driver


def close_browser(browser: WebDriver):
    print('退出程序')
    # browser.close()
    browser.quit()


def save_cookies(browser: WebDriver):
    browser.refresh()
    cookies = browser.get_cookies()
    if len(cookies) <= 0:
        return
    with open('./cookies.txt', 'w', encoding='utf-8') as f:
        for cookie in cookies:
            f.write(json.dumps(cookie) + '\n')


def load_cookies(browser: WebDriver):
    if not os.path.exists('./cookies.txt'):
        return
    browser.delete_all_cookies()
    with open('./cookies.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            if line is not None:
                browser.add_cookie(json.loads(line))


def save_local_storage(browser: WebDriver, name):
    value = browser.execute_script(f'return localStorage.getItem("{name}")')
    if value:
        with open('./localStorage.txt', 'w', encoding='utf-8') as f:
            f.write(name + '=' + value + '\n')
    else:
        load_local_storage(browser, name)


def load_local_storage(browser: WebDriver, name):
    if not os.path.exists('./cookies.txt'):
        return
    value = ''
    with open('./localStorage.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            if line is not None and line.startswith(name):
                value = line.replace(name + '=', '').replace('\n', '')
    browser.execute_script(f'localStorage.setItem("{name}", \'{value}\')')


def save_session_storage(browser: WebDriver, name):
    value = browser.execute_script(f'return sessionStorage.getItem("{name}")')
    with open('./sessionStorage.txt', 'w', encoding='utf-8') as f:
        f.write(name + '=' + value + '\n')


def load_session_storage(browser: WebDriver, name):
    if not os.path.exists('./cookies.txt'):
        return
    value = ''
    with open('./sessionStorage.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            if line is not None and line.startswith(name):
                value = line.replace(name + '=', '').replace('\n', '')
    browser.execute_script(f'sessionStorage.setItem("{name}", \'{value}\')')


# 随机打开内容item
def random_click(page: WebDriver, info_list: [], css_selector: str=None, limit: int=3):
    count = 0
    origin_page = page.current_window_handle
    while count < limit and count < len(info_list):
        count = count + 1
        idx = random.randint(0, len(info_list) - 1)
        # 鼠标移动到对应元素
        # webdriver.ActionChains(page).move_to_element(info_list[idx]).perform()
        # 获取a标签链接
        href = info_list[idx].get_attribute('href')
        page.execute_script(f'window.open("{href}", "_blank");')
        # 暂停3秒
        time.sleep(3)
        # 新标签页
        window_handles = page.window_handles
        current_page = window_handles[-1]
        # 切换标签页
        page.switch_to.window(current_page)
        # 执行回调函数
        if css_selector is not None:
            info_items = page.find_elements(By.CSS_SELECTOR, css_selector)
            random_click(page, info_items, None, limit)
        # 关闭标签页
        page.close()
        page.switch_to.window(origin_page)

